package models.weixin.crop;

import helper.GlobalConfig;
import helper.UrlHelper;
import models.constants.DeletedStatus;
import models.enums.WxcpAppStatus;
import models.enums.WxcpAppType;
import play.Logger;
import play.db.jpa.Model;

import javax.persistence.*;
import java.util.Date;
import java.util.List;

/**
 * 企业号 公司应用配置信息.
 * <p/>
 * 公司可以在我们系统中运行多个应用，应用的定义由枚举
 */
@Entity
@Table(name = "wxcp_corp_apps")
public class CorpApp extends Model {

    /**
     * 企业号公司.
     */
    @ManyToOne
    @JoinColumn(name = "corp_id")
    public Corp corp;

    @Column(name = "name", length = 100)
    public String name;

    /**
     * 永久授权码，通过get_permanent_code获取
     */
    @Column(name = "permanent_code", length = 100)
    public String permanentCode;


    /**
     * 子域名值.
     *
     * 随机生成一个10位全小写的数字字母值，用于生成URL，如：
     *     http://dua319jy32.xxx.com
     * 系统通过dua319jy32定位找到CorpApp.
     */
    @Column(name = "subdomain", length = 20)
    public String subdomain;

    /**
     * 企业号应用类型
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "app_type", length = 20)
    public WxcpAppType appType;



    /**
     * 微信企业号应用ID.
     */
    @Column(name = "wx_agent_id", length = 20)
    public String wxAgentId;

    /**
     * 微信企业号应用默认部门.
     *
     * 建立新用户时指定为默认部门.
     */
    @Column(name = "default_wx_dept_id", length = 20)
    public Integer defaultWxDeptId;

    /**
     * 配置回调模式的Token.
     * <p/>
     * Token可由企业任意填写，用于生成签名.
     */
    @Column(name = "token", length = 50)
    public String token;

    /**
     * EncodingAESKey用于消息体的加密，是AES密钥的Base64编码.
     */
    @Column(name = "aes_key", length = 50)
    public String aesKey;

    /**
     * 应用状态.
     *
     * 单个应用可以被关闭，这取决于客户所购买的服务.
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "status", length = 20)
    public WxcpAppStatus status;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted = DeletedStatus.UN_DELETED;
    /**
     * 失效时间.
     *
     * 如果有值，则在此值之前此应用是可用的，但还需要检查status.
     * 如果无值，则永久有效.
     */
    @Column(name = "expired_at")
    public Date expiredAt;

    /**
     * 创建时间.
     */
    @Column(name = "created_at")
    public Date createdAt;

    /**
     * 更新时间.
     */
    @Column(name = "updated_at")
    public Date updatedAt;


    /**
     * 来自应用套件激活的应用.
     */
    @Column(name = "from_suite")
    public Boolean fromSuite;


    /**
     * 得到应用的请求URL中HOST地址.
     */
    public String urlHost() {
        return subdomain + "." + GlobalConfig.WEIXIN_BASE_DOMAIN;
    }

    public static CorpApp findFirstByCorp(Corp corp) {
        return CorpApp.find("corp = ?" , corp).first();
    }
    /**
     * 通过子域名得到CorpApp.
     */
    public static CorpApp findByHostName(final String hostname) {
        final String subdomain = UrlHelper.getSubdomain(hostname);
        return cache.CacheHelper.getCache("CorpApp_Subdomain@" + subdomain, new cache.CacheCallBack<CorpApp>() {
            @Override
            public CorpApp loadData() {
                CorpApp corpApp = CorpApp.find("subdomain=? and status=? and (expiredAt >= ? or expiredAt is null)",
                        subdomain, WxcpAppStatus.OPEN, new Date()
                ).first();
                Logger.info("corpApp.corp=" + corpApp.corp); //手工显示一下corp信息以缓存
                return corpApp;
            }
        });
    }

    public static CorpApp findByType(Corp corp, WxcpAppType type) {
        return CorpApp.find("corp=? and appType=? and status=? order by id desc", corp, type, WxcpAppStatus.OPEN).first();
    }

    public static CorpApp findFirstAvailable() {
        return CorpApp.find("status=? order by id desc", WxcpAppStatus.OPEN).first();
    }
    public static List<CorpApp> findCorpAppByCropid(Long id) {
        return CorpApp.find(" corp.id= ? ", id).fetch();
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("CorpApp{");
        sb.append("corp=").append(corp);
        sb.append(", name='").append(name).append('\'');
        sb.append(", permanentCode='").append(permanentCode).append('\'');
        sb.append(", subdomain='").append(subdomain).append('\'');
        sb.append(", appType=").append(appType);
        sb.append(", wxAgentId='").append(wxAgentId).append('\'');
        sb.append(", token='").append(token).append('\'');
        sb.append(", aesKey='").append(aesKey).append('\'');
        sb.append(", status=").append(status);
        sb.append(", expiredAt=").append(expiredAt);
        sb.append(", createdAt=").append(createdAt);
        sb.append(", updatedAt=").append(updatedAt);
        sb.append(", fromSuite=").append(fromSuite);
        sb.append('}');
        return sb.toString();
    }
    //查找所有应用状态是可用的状态
    public  static List<CorpApp> loadCorpApp(){
       return CorpApp.find("status=?", WxcpAppStatus.OPEN).fetch();
    }

    public  static List<CorpApp> loadCorpAppId(long corpId){
        return CorpApp.find("corp.id =? and deleted=?", corpId, DeletedStatus.UN_DELETED).fetch();
    }
    //根据ID查找相对应的CorpApp
    public static CorpApp findByCorpAppId(long id) {
        return CorpApp.find("id=? and deleted=?", id, DeletedStatus.UN_DELETED).first();
    }
}
